package workgroup

type RunFunc func(<-chan struct{}) error

type Group struct {
	fns []RunFunc
}

func (g *Group) Add(fn RunFunc) {
	g.fns = append(g.fns, fn)
}

func (g *Group) Run() error {
	if len(g.fns) == 0 {
		return nil
	}

	stop := make(chan struct{})
	done := make(chan error, len(g.fns))
	defer close(done)

	for _, fn := range g.fns {
		go func(fn RunFunc) {
			done <- fn(stop)
		}(fn)
	}

	var err error
	for size := 0; size < cap(done); size++ {
		if err == nil {
			err = <-done
		} else {
			<-done
		}

		if size == 0 {
			close(stop)
		}
	}

	return err

}
